package com.hangxingliu.exceltools;

import com.hangxingliu.exceltools.ExcelAPI.PreviewInfo;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map.Entry;
import javax.swing.JOptionPane;

public class Controller {

	private MainWindow wind;
	
	private String filePath = null;
	private ExcelAPI excel = null;
	private String selectedSheetName = null;
	private HelpDialog helpDialog = null;
	private ExcelAPI.DuplicationInfo duplication = null;

	public Controller(MainWindow wind) {
		this.wind = wind;
	}
	
	public void onClickOpen() {
		filePath = Utils.showExcelPicker4Load(wind);
		if(filePath == null || filePath.length() <= 0)
			return;

		if(!openExcel()) return;

		wind.attr.updateFilePath(filePath);
		wind.attr.updateSheetNames(excel.sheetNames);
		selectSheet(excel.sheetNames[0]);

		closeExcel();
	}

	public void onClickSave() {
		if(duplication == null) {
			error("请先查找重复数据!");
			return;
		}

		String exportTo = Utils.showExcelPicker4Save(wind, "重复数据.xls");
		if(exportTo == null || exportTo.length() <= 0)
			return;

		if(!openExcel()) return;

		try{
			excel.exportDuplicatedItems(duplication, exportTo);
			message("导出成功!", exportTo);
		} catch(Exception e) {
			e.printStackTrace();
			error("导出数据失败!\n" + e.getMessage());
		}

		closeExcel();
	}

	public void onClickFind() {
		Integer startRow = wind.attr.getStartRow();
		if(startRow == null || startRow < 1) {
			error("请输入正确的起始行!");
			return;
		}

		int col = wind.attr.getColumn();
		if(col < 0) {
			error("请选择有效的列!");
			return;
		}

		findDuplication(startRow - 1, col);
	}
	
	public void onClickHelp() {
		if(helpDialog == null)
			helpDialog = new HelpDialog();
		int x = wind.getX(), y = wind.getY(),
			w = wind.getWidth(), h = wind.getHeight();

		x += (int) (w * 0.1);
		w = (int) (w * 0.8);
		y += (int) (h * 0.15);
		h = (int) (h * 0.7);
		helpDialog.showWind(x, y, w, h);
	}

	public void onTableColumnClick(int columnId) { wind.attr.setColumn(columnId); }
	public void onUpdateSheetName(String sheetName) { selectSheet(sheetName); }
	public void onWindowClosing() { closeExcel(); if(helpDialog != null) helpDialog.dispose(); }
	public void onUpdatePreviewCheckBox() { preview(selectedSheetName); }
	
	//=================================

	public boolean openExcel() {
		if(excel != null && !excel.isClosed)
			return true;

		if(filePath == null || filePath.length() <= 0)
			return false;

		excel = ExcelAPI.Open(filePath);
		if(!excel.success) {
			error("载入Excel文件出错!\n" + excel.errorInformation);
			return false;
		}
		if(excel.sheetNames == null || excel.sheetNames.length <= 0) {
			error("Excel文件内未包含任何工作表!");
			excel.close();
			excel = null;
			return false;
		}

		return true;
	}
	public void closeExcel() {
		if(excel == null)
			return;
		excel.close();
		excel = null;
	}

	public void selectSheet(String sheetName) {
		selectedSheetName = sheetName;
		if(!preview(sheetName))
			selectedSheetName = null;
	}

	public boolean preview(String sheetName) {
		if(!openExcel())
			return false;

		PreviewInfo info = excel.preview(sheetName, wind.attr.isPreviewAllData() ? 0 : 10);
		if(info.col <= 0 || info.row <= 0 ) {
			String title[] = new String[]{ "无数据" };
			wind.attr.updatePreviewTable(title, new String[][]{ { "无数据" } });
			wind.attr.updateDuplicatedColumns(new String[0]);

			error(String.format("工作表 %s 不包含任何列!", sheetName));
			return false;
		}

		wind.attr.updatePreviewTable(info.title, info.data);

		String[] columns = new String[info.data[0].length];
		for(int i = 0 ; i < columns.length ; i ++ )
			columns[i] = Utils.columnInt2Str(i) + ": " + info.data[0][i];

		wind.attr.updateDuplicatedColumns(columns);

		closeExcel();

		return true;
	}

	public boolean findDuplication(int startRow, int column) {
		if(!openExcel())
			return false;

		if(selectedSheetName == null) {
			error("请先选择有效的工作表!");
			return false;
		}

		duplication = excel.findDuplication(selectedSheetName, startRow, column);
		Iterator<Entry<String, ArrayList<String>>> it = duplication.duplication.entrySet().iterator();

		int count = 0, countAll = 0;
		StringBuilder log = new StringBuilder();
		while(it.hasNext()) {
			Entry<String, ArrayList<String>> item = it.next();
			ArrayList<String> infoArray = item.getValue();
			log.append(item.getKey() + " >  ");
			for (String info : infoArray)
				log.append("  " + info);
			log.append('\n');
			count++;
			countAll+=infoArray.size();
		}
		log.append(String.format("\n重复记录: %d, 总计 %d 条", count, countAll));
		wind.attr.updateOutput(log);

		closeExcel();
		return true;
	}


	private void error(String string) { 
		JOptionPane.showMessageDialog(wind, string, "错误", JOptionPane.ERROR_MESSAGE); }
	private void message(String title, String string) { 
		JOptionPane.showMessageDialog(wind, string, title, JOptionPane.INFORMATION_MESSAGE); }


}
